import {Form, Input, Select, Button, Tree, Switch, Col, Row, message} from 'antd';
import React from 'react';
import * as Request from '../../Server/SystemManger';
import qs from 'qs'
import * as Utils from '../../common/utils';
import * as Const from '../../common/const'

const FormItem = Form.Item;
const Option = Select.Option;;
const defaultPage = {page: 0, size: 50};
const TreeNode = Tree.TreeNode;
const reg = /^(?!([A-Z]*|[a-z]*|[0-9]*|[!-/:-@\[-`{-~]*|[A-Za-z]*|[A-Z0-9]*|[A-Z!-/:-@\[-`{-~]*|[a-z0-9]*|[a-z!-/:-@\[-`{-~]*|[0-9!-/:-@\[-`{-~]*)$)[A-Za-z0-9!-/:-@\[-`{-~]{8,20}$/

class UserForms extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            title: "新增用户",
            roleOptions: [],
            companyOptions: [],
            user: undefined,
            expandedKeys: [],
            status: 0,//用户状态 0:禁用 1:启用,默认禁用
            statusChecked: false
        };
    }

    componentWillMount() {
        this.getRoleAndCompanyList();
        this.initUser();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }

    getRoleAndCompanyList = () => {
        Request.saveUserGo().then(res => {
            if(res && Const.REQUEST_SUCCESS == res.code && res.data){
                this.setState({
                    roleOptions:res.data.roleList,
                    companyOptions:res.data.companyList,
                });
            }
        });
    }


    initUser = () => {
        if (this.props.id) {
            Request.getUserById(this.props.id).then(res => {
                if (res && Const.REQUEST_SUCCESS == res.code) {
                    this.setState({
                        user: res.data,
                        passwordDisabled: true,
                        status: res.data.status,
                        statusChecked: res.data.status ? true : false,
                    });
                }
            });
        }
    }

    handleSubmit = (e) => {
        const _this = this;
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err){
                values.username = values.username.replace(/\s*/g,"");
                const params = {
                    ...values,
                    status: _this.state.status,
                };
                Object.values(params).map(v => {
                    return v !== "";
                })
                Request.editOrSaveUser(qs.stringify(params, {indices: false})).then(res => {
                    if (res && Const.REQUEST_SUCCESS == res.code) {
                        this.props.cancel(true);
                        message.success(this.props.id ? '编辑用户成功' : '新增用户成功', 1);
                    }
                })
            }
        });
    }

    validatePassword = (rule, value, callback) => {
        if(!value || !value.length) {callback();return;}
        if (!reg.test(value)) {
            callback('密码包含大写字母、小写字母、数字、特殊符号中的至少三类，且长度在8到20之间!');
        } else {
            callback();
        }
        if(this.props.form.getFieldValue('confirmPassword')){
            this.props.form.validateFields(['confirmPassword'],{ force: true });
        }
    }
    compareToFirstPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入的密码不一致!');
        } else {
            callback();
        }
    }
    validateUserName = (rule, value, callback) => {
        if (value && value.length) {
            const params = {username: value};
            this.props.id && (params.id = this.props.id)
            Request.validatorUser(qs.stringify(params)).then(res => {
                if (res && Const.REQUEST_SUCCESS == res.code && !res.data) {
                    callback(Const.VALIDATOR_FAIL_TIP);
                } else {
                    callback();//注意:回调函数必须调用
                }
            });
        } else {
            callback();
        }
    }
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children && item.children.length) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            delete item.children;
            return <TreeNode title={item.title} key={item.key} dataRef={item}/>;
        });
    }

    onSelect = (selectedKeys, info) => {
        this.setState({selectedKeys});
    }

    onCheck = (checkedKeys, e) => {
        let checkedId = [];
        e.checkedNodes.map(node => {
            checkedId.push(node.props.dataRef.id || node.props.id);
        });
        this.setState({checkedKeys, checkedId});
    }
    onExpand = (expandedKeys) => {
        this.setState({expandedKeys});
    }

    getRoleIds = (roleList, roleids = []) => {
        roleList.map(item => {
            roleids.push(item.id + '')
        })
        return roleids;
    }
    statusChange = (checked) => {
        this.setState({
            status: checked ? 1 : 0,
            statusChecked: checked
        });
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const roleOptions = this.state.roleOptions.map(d => <Option value={d.id + ''} key={d.id + ''}>{d.name}</Option>);
        const companyOptions = this.state.companyOptions.map(d => <Option value={d.id + ''} key={d.id + ''}>{d.name}</Option>);
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };

        return (
            <div>
                <FormItem>
                    {getFieldDecorator('id', {
                        initialValue: this.props.id,
                    })(
                        <Input type={'hidden'}/>
                    )}
                </FormItem>
                <Form onSubmit={this.handleSubmit}>
                    <Row>
                        <Col>
                            <FormItem
                                {...formItemLayout}
                                label="用户名"
                            >
                                {getFieldDecorator('username', {
                                    initialValue: this.state.user && this.state.user.username,
                                    rules: [{
                                        required: true, message: '请输入用户名!',
                                    }, {
                                        validator: this.validateUserName,
                                    }],
                                })(
                                    <Input disabled={this.props.disable || (this.props.id ? true : false)} maxLength={255}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            {!this.props.disable && <FormItem
                                {...formItemLayout}
                                label="密码"
                            >
                                {getFieldDecorator('password', {
                                    rules: [{
                                        required: this.props.id ? false : true, message: '请输入密码!',
                                    }, {
                                        validator: this.validatePassword,
                                    }]
                                })(
                                    <Input type={'password'} maxLength={255}/>
                                )}
                            </FormItem>}
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            {!this.props.id && <FormItem
                                {...formItemLayout}
                                label="确认密码"
                            >
                                {getFieldDecorator('confirmPassword', {
                                    rules: [{
                                        required: true, message: '请再次输入密码确认!',
                                    }, {
                                        validator: this.compareToFirstPassword,
                                    }],
                                    initialValue: this.state.user && this.state.user.password
                                })(
                                    <Input type={'password'} maxLength={255}/>
                                )}
                            </FormItem>}
                        </Col>
                        <Col >
                            <FormItem
                                {...formItemLayout}
                                label={'角色配置'}
                            >
                                {getFieldDecorator('roleids', {
                                    initialValue: this.state.user && this.getRoleIds(this.state.user.roleList),
                                })(
                                    <Select
                                        showSearch
                                        placeholder="请选择"
                                        optionFilterProp="children"
                                        disabled={this.props.disable}
                                        mode="multiple"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >
                                        {roleOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col >
                            <FormItem
                                {...formItemLayout}
                                label={'分部配置'}
                            >
                                {getFieldDecorator('companyid', {
                                    rules: [{required: true, message: '请选择分部配置！'}],
                                    initialValue: this.state.user && this.state.user.sysCompany && this.state.user.companyid + '',
                                })(
                                    <Select
                                        showSearch
                                        placeholder="请选择"
                                        optionFilterProp="children"
                                        disabled={this.props.disable}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                    >
                                        {companyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                {...formItemLayout}
                                label={'状态'}
                            >
                                {getFieldDecorator('status')(
                                    <Switch
                                        checkedChildren="启用"
                                        unCheckedChildren="禁用"
                                        onChange={this.statusChange}
                                        checked={this.state.statusChecked}
                                        disabled={this.props.disable}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    {<FormItem style={{textAlign:'center'}}>
                        {!(this.props.id && this.props.disable) &&
                        <Button type="primary" htmlType="submit">保存</Button>}
                        <Button type="primary" onClick={() => this.props.cancel()}>返回</Button>
                    </FormItem>}
                </Form>
            </div>
        );
    }
}

const WrappedUserForms = Form.create()(UserForms);

export default WrappedUserForms;